import { Injectable } from '@nestjs/common';
import { CreateFocusDto } from './dto/create-focus.dto';
import { UpdateFocusDto } from './dto/update-focus.dto';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { Focus } from './entities/focus.entity';
import { User } from '../user/entities/user.entity';
import { BusinessException } from '../../common/exceptions/business.exception';
import { ErrorCode } from '../../common/errorcode';

@Injectable()
export class FocusService {
  constructor(
    @InjectRepository(Focus) private focusRepository: Repository<Focus>,
    @InjectRepository(User) private userRepository: Repository<User>
  ) { }

  // 关注用户
  async follow(createFocusDto: CreateFocusDto) {
    const { follower_id, following_id } = createFocusDto;

    // 检查是否已经关注
    const existingFocus = await this.focusRepository.findOne({
      where: {
        follower_id,
        following_id
      }
    });

    if (existingFocus) {
      throw new BusinessException('您已经关注了该用户', ErrorCode.FORBIDDEN);
    }

    // 检查被关注用户是否存在
    const followingUser = await this.userRepository.findOne({
      where: { userid: following_id }
    });

    if (!followingUser) {
      throw new BusinessException('被关注用户不存在', ErrorCode.NULL_ERROR);
    }

    // 不能关注自己
    if (follower_id === following_id) {
      throw new BusinessException('不能关注自己', ErrorCode.FORBIDDEN);
    }

    const focus = this.focusRepository.create(createFocusDto);
    return await this.focusRepository.save(focus);
  }

  // 取消关注
  async unfollow(follower_id: string, following_id: string) {
    const focus = await this.focusRepository.findOne({
      where: {
        follower_id,
        following_id
      }
    });

    if (!focus) {
      throw new BusinessException('您未关注该用户', ErrorCode.FORBIDDEN);
    }

    await this.focusRepository.remove(focus);
    return { message: '取消关注成功' };
  }

  // 查询用户的关注列表（用户关注了哪些人）
  async getFollowingList(userid) {
    const follows = await this.focusRepository.find({
      where: { follower_id: userid.userid }
    });

    // 获取被关注用户的详细信息
    const followingUsers: any[] = [];
    for (const follow of follows) {
      const user = await this.userRepository.findOne({
        where: { userid: follow.following_id }
      });
      if (user) {
        followingUsers.push({
          ...user,
          follow_time: follow.create_time
        });
      }
    }

    return followingUsers;
  }

  // 查询用户的粉丝列表（哪些人关注了该用户）
  async getFollowersList(userid: string) {
    const followers = await this.focusRepository.find({
      where: { following_id: userid }
    });

    // 获取粉丝用户的详细信息
    const followerUsers: any[] = [];
    for (const follower of followers) {
      const user = await this.userRepository.findOne({
        where: { userid: follower.follower_id }
      });

      if (user) {
        const isFollowing = await this.isFollowing(userid, user.userid)
    console.log('这个人关注了',isFollowing);

        followerUsers.push({
          ...user,
          follow_time: follower.create_time,
          isfocus: isFollowing
        });
      }
    }

    return followerUsers;
  }

  // 检查是否关注了某个用户
  async isFollowing(follower_id: string, following_id: string) {
    const focus = await this.focusRepository.findOne({
      where: {
        follower_id:follower_id,
        following_id:following_id
      }
    });
    
    return Boolean(focus);
  }

  // 获取关注统计
  async getFollowStats(userid: string) {
    const followingCount = await this.focusRepository.count({
      where: { follower_id: userid }
    });

    const followersCount = await this.focusRepository.count({
      where: { following_id: userid }
    });

    return {
      following_count: followingCount,
      followers_count: followersCount
    };
  }

  // 切换关注状态
  async toggleFollow(follower_id: string, following_id: string) {
    const focus = await this.focusRepository.findOne({
      where: { follower_id, following_id }
    });
    if (focus) {
      await this.focusRepository.remove(focus);
      return { message: '已取消关注', isFocus: false };
    } else {
      // 检查不能关注自己
      if (follower_id === following_id) {
        throw new BusinessException('不能关注自己', ErrorCode.FORBIDDEN);
      }
      const followingUser = await this.userRepository.findOne({ where: { userid: following_id } });
      if (!followingUser) {
        throw new BusinessException('被关注用户不存在', ErrorCode.NULL_ERROR);
      }
      const newFocus = this.focusRepository.create({ follower_id, following_id });
      await this.focusRepository.save(newFocus);
      return { message: '已关注', isFocus: true };
    }
  }

  // 原有的方法保留但不使用
  create(createFocusDto: CreateFocusDto) {
    return this.follow(createFocusDto);
  }

  findAll() {
    return `This action returns all focus`;
  }

  findOne(id: number) {
    return `This action returns a #${id} focus`;
  }

  update(id: number, updateFocusDto: UpdateFocusDto) {
    return `This action updates a #${id} focus`;
  }

  remove(id: number) {
    return `This action removes a #${id} focus`;
  }
}
